#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

bool flag = true;

void *A(void *args)
{
    while (true)
    {
        sleep(1);

        pthread_mutex_lock(&mutex);
        if(!flag)
            pthread_cond_wait(&cond, &mutex);
      
        cout << "I am A" << endl;
        flag = false;
        pthread_cond_signal(&cond);
        
        pthread_mutex_unlock(&mutex);
    }
}

void *B(void *args)
{
    while (true)
    {
        sleep(1);

        pthread_mutex_lock(&mutex);

        if(flag)
            pthread_cond_wait(&cond, &mutex);
        
        cout << "I am B" << endl;
        flag = true;
        pthread_cond_signal(&cond);

        pthread_mutex_unlock(&mutex);
    }
}

int main()
{

    pthread_t tid1, tid2;

    int n = pthread_create(&tid1, nullptr, A, nullptr);
    int m = pthread_create(&tid2, nullptr, B, nullptr);

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);

    return 0;
}